package org.example.wikwok.controller;


import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletResponse;
import org.example.wikwok.common.JwtProperties;
import org.example.wikwok.common.JwtUtil;
import org.example.wikwok.common.UtilityClasses;
import org.example.wikwok.pojo.Result;
import org.example.wikwok.pojo.Video;
import org.example.wikwok.pojo.VideoInfo;
import org.example.wikwok.service.CommentService;
import org.example.wikwok.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.datatransfer.DataFlavor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Timestamp;
import java.util.List;

//处理视频上传的HTTP请求。
@RestController
@RequestMapping("/video")
public class VideoController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private CommentService commentService;
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result<Object> upload(String token,String title,String description,MultipartFile file) {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        //判断文件是否为空
        if(file.isEmpty()) return Result.buildFailure(6666);
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        String fileName = file.getOriginalFilename();
        String saveFileName = System.currentTimeMillis() + "_"+fileName;
        File dir = new File(UtilityClasses.getDir());
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(UtilityClasses.getUploadDir()+ saveFileName));
            Video video = new Video(title,userId,new Timestamp(System.currentTimeMillis()),saveFileName,description);
            int videoId = videoService.upload(video,userId);
            if(videoId!=-1){
                return Result.ok(videoId,2101);
            }
            //标题已存在
            else  return Result.buildFailure(2103);
        } catch (Exception e) {
            return Result.buildFailure(2102);
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result<Object> delete(String token,String videoId) {
        int videoIdInt = Integer.parseInt(videoId);
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        try{
            if(videoService.delete(videoIdInt,userId))return Result.ok(null,2111);
    else throw new Exception("User not authorized to delete video(2113)");
        }catch (Exception e){
            if(e.getMessage().contains("2113"))return Result.buildFailure(2113);
            else return Result.buildFailure(2112);
        }
    }

@RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<Object> list(String token,String offset) {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        int OFFSET=Integer.parseInt(offset);
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        try{
            List<VideoInfo> videoInfoList=videoService.list(userId,OFFSET);
            if(videoInfoList.isEmpty()) return Result.buildFailure(2404);
            int code=videoInfoList.size()>=5?2401:2403;
            //如果不够5条返回2403，如果够5条返回2401,如果为空返回2404
             return Result.ok(videoInfoList,code);
        }catch (Exception e){
            return Result.buildFailure(2402);
        }
    }
    @RequestMapping(value = "/comments", method = RequestMethod.GET)
    public Result<Object> comments(String token,String videoId) {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        try{
            return Result.ok(commentService.comments(userId,videoId),3101);
        }catch (Exception e){
            return Result.buildFailure(3102);
        }
    }
    @RequestMapping(value="secendComments",method=RequestMethod.GET)
    public Result<Object> secendComments(String token,String videoId,String commentId) {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        try{
            return Result.ok(commentService.secendComments(userId,videoId,commentId),3401);
        }catch (Exception e){
            return Result.buildFailure(3402);
        }
    }
}
